/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.suli.toHouse.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import me.zhengjie.suli.inventory.domain.Inventory;
import me.zhengjie.suli.inventory.repository.InventoryRepository;
import me.zhengjie.suli.location.domain.Location;
import me.zhengjie.suli.location.repository.LocationRepository;
import me.zhengjie.suli.toHouse.domain.Receipt;
import me.zhengjie.suli.toHouse.service.ReceiptService;
import me.zhengjie.suli.toHouse.service.dto.ReceiptQueryCriteria;
import me.zhengjie.util.CommonUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @website https://eladmin.vip
* @author WYH
* @date 2024-02-01
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "入库单管理")
@Slf4j
@RequestMapping("/api/receipt")
public class ReceiptController {

    private final ReceiptService receiptService;
    private final CommonUtil commonUtil;
    private final LocationRepository locationRepository;
    private final InventoryRepository inventoryRepository;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('receipt:list')")
    public void exportReceipt(HttpServletResponse response, ReceiptQueryCriteria criteria) throws IOException {
        receiptService.download(receiptService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询入库单")
    @ApiOperation("查询入库单")
    @PreAuthorize("@el.check('receipt:list')")
    public ResponseEntity<Object> queryReceipt(ReceiptQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(receiptService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增入库单")
    @ApiOperation("新增入库单")
    @PreAuthorize("@el.check('receipt:add')")
    public ResponseEntity<Object> createReceipt(@Validated @RequestBody Receipt resources){
        return new ResponseEntity<>(receiptService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改入库单")
    @ApiOperation("修改入库单")
    @PreAuthorize("@el.check('receipt:edit')")
    public ResponseEntity<Object> updateReceipt(@Validated @RequestBody Receipt resources){
        receiptService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除入库单")
    @ApiOperation("删除入库单")
    @PreAuthorize("@el.check('receipt:del')")
    public ResponseEntity<Object> deleteReceipt(@RequestBody String[] ids) {
        receiptService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 采购入库单
     *
     * @param param
     * @return
     */
    @AnonymousPostMapping(value = "/procure")
    @ApiOperation("采购入库单")
    public String procureReceipt(@RequestBody String param) {
        return receiptService.procureReceipt(param);
    }

    /**
     * 扫描退货单发送至sccs，客户退货入库
     *
     * @param param
     * @return
     */
    @AnonymousPostMapping(value = "/customer-return")
    @ApiOperation("客户退货入库")
    public String customerReturn(String param) {
        return receiptService.customerReturn(param);
    }

    @PostMapping(value = "/queryReceipt")
    @ApiOperation("入库单号请求入库单数据")
    public ResponseEntity<Object> queryReceipt(@RequestBody String poCode) {
        return new ResponseEntity<>(receiptService.queryReceipt(poCode), HttpStatus.OK);
    }

    @PostMapping(value = "/receiveToRCV")
    @ApiOperation("入库到暂存区")
    public ResponseEntity<Object> receiveToRCV(@RequestBody String param) {
        return new ResponseEntity<>(receiptService.receiveToRCV(param), HttpStatus.OK);
    }

    @PostMapping(value = "/zuPanConfirm")
    @ApiOperation("申请组盘")
    public ResponseEntity<Object> zuPanConfirm(@RequestBody String param) {
        return new ResponseEntity<>(receiptService.zuPanConfirm(param), HttpStatus.OK);
    }

    @PostMapping(value = "/rePushSccs")
    @ApiOperation("重推")
    public ResponseEntity<Object> rePushSccs(@RequestBody String mtList) {
        return new ResponseEntity<>(receiptService.rePushSccs(mtList), HttpStatus.OK);
    }

    @AnonymousPostMapping(value = "/tray")
    @ApiOperation("初始化料箱入库")
    public ResponseEntity<Object> chuShiHua(@RequestBody String locationCode) {
        return new ResponseEntity<>(receiptService.chuShiHua(locationCode), HttpStatus.OK);
    }

    @AnonymousPostMapping(value = "/get-trayCode")
    @ApiOperation("获取输送线料箱号")
    public ResponseEntity<Object> getTrayCode() {
//        for (int i = 0; i < 83; i++) {
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("page",i+1);
//            jsonObject.put("size",50);
////            jsonObject.put("isEmpty",false);
////            jsonObject.put("isShelfStorage",true);
//            String s = commonUtil.httpPost("http://10.198.76.25:9003/ess-api/monitor/location/query", jsonObject);
//            JSONObject jsonObjects = JSON.parseObject(s);
//            JSONObject jsonObject1 = jsonObjects.getJSONObject("data");
//            JSONArray data = jsonObject1.getJSONArray("locations");
//            for (Object datum : data) {
//                JSONObject jsonObject7 = JSON.parseObject(JSON.toJSONString(datum));
//                Location locationByLocationCode = locationRepository.findLocationByLocationCode(jsonObject7.getString("code"));
//                if (null == locationByLocationCode){
//                    System.out.println(datum);
//                }
//                if (null != jsonObject7.getString("containerCode") && !"".equals(jsonObject7.getString("containerCode"))){
//                    locationByLocationCode.setTrayCode(jsonObject7.getString("containerCode"));
//                    locationByLocationCode.setStatus(3);
//                    locationRepository.save(locationByLocationCode);
//                }
//            }
//        }
        return new ResponseEntity<>(receiptService.getTrayCode(), HttpStatus.OK);
    }

    /** 成本中心入库测试  */
    @AnonymousPostMapping(value = "/procureCostCenterToHouse")
    @ApiOperation("采购入库单")
    public String procureCostCenterToHouse(@RequestBody String param) {
        return receiptService.procureCostCenterToHouse(param);
    }

    /** 多余空料箱回库 */
    @PostMapping(value = "/emptyBoxHuiKu")
    @ApiModelProperty("多余空料箱回库")
    public ResponseEntity<Object> emptyBoxHuiKu(@RequestBody String param){
        return new ResponseEntity<>(receiptService.emptyBoxHuiKu(param), HttpStatus.OK);
    }

    @PostMapping(value = "/selectReceiptById")
    @ApiModelProperty("查询当前入库单有多少完成的")
    public ResponseEntity<Object> selectReceiptById(@RequestBody String param){
        return new ResponseEntity<>(receiptService.selectReceiptById(param), HttpStatus.OK);
    }

    @AnonymousPostMapping(value = "/getReceiptDetailInfo")
    @ApiModelProperty("查询当前入库单有多少完成的")
    public ResponseEntity<Object> getReceiptDetailInfo(@RequestBody String param){
        return new ResponseEntity<>(receiptService.getReceiptDetailInfo(param), HttpStatus.OK);
    }

    @AnonymousPostMapping(value = "/check")
    @ApiModelProperty("对库存")
    public ResponseEntity<Object> inventoryCheck(){
        for (int i = 0; i < 83; i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("page",i+1);
            jsonObject.put("size",50);
//            jsonObject.put("isEmpty",false);
//            jsonObject.put("isShelfStorage",true);
            String s = commonUtil.httpPost("http://10.198.76.25:9003/ess-api/monitor/location/query", jsonObject);
            JSONObject jsonObjects = JSON.parseObject(s);
            JSONObject jsonObject1 = jsonObjects.getJSONObject("data");
            JSONArray data = jsonObject1.getJSONArray("locations");
            for (Object datum : data) {
                JSONObject jsonObject7 = JSON.parseObject(JSON.toJSONString(datum));
                Location locationByLocationCode = locationRepository.findLocationByLocationCode(jsonObject7.getString("code"));
                if (null == locationByLocationCode){
                    System.out.println(datum);
                }
                if (null != jsonObject7.getString("containerCode") && !"".equals(jsonObject7.getString("containerCode"))){
                    locationByLocationCode.setTrayCode(jsonObject7.getString("containerCode"));
                    locationByLocationCode.setStatus(3);
                    locationRepository.save(locationByLocationCode);
                }
            }
        }
        List<Location> all1 = locationRepository.findAll();
        List<String> collect = all1.stream().map(Location::getTrayCode).distinct().collect(Collectors.toList());
        List<Inventory> all = inventoryRepository.findAll();
        for (Inventory inventory : all) {
            if (!inventory.getWarehouseLocation().equals("暂存区")){
                try{
                    Location locationByLocationCode = locationRepository.findByTrayCode(inventory.getTrayCode());
                    if (null != locationByLocationCode){
                        locationByLocationCode.setStatus(1);
                        inventory.setWarehouseLocation(locationByLocationCode.getLocationCode());
                        inventory.setLocationCode(locationByLocationCode.getLocationCode());
                        locationRepository.save(locationByLocationCode);
                        inventoryRepository.save(inventory);
                    }
                }catch (Exception e){
                    log.info(("异常库存") + inventory.getBoxNumber());
                }
            }
        }
        log.info("核对成功");
        return null;
    }

    @AnonymousPostMapping(value = "/sendPOCode")
    public ResponseEntity<Object> sendPOCode(@RequestBody String param) {
        return new ResponseEntity<>(receiptService.sendPOCode(param), HttpStatus.OK);
    }

    @AnonymousPostMapping(value = "/receiveBoxNumberFromPDA")
    public ResponseEntity<Object> receiveBoxNumberFromPDA(@RequestBody String param) {
        return new ResponseEntity<>(receiptService.receiveBoxNumberFromPDA(param), HttpStatus.OK);
    }
}
